package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.li.work.domain.vo.WorkDeptUserVO;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.*;
import com.ruoyi.teaching.mapper.*;
import com.ruoyi.teaching.service.PlatformCCourseService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class PlatformCCourseServiceImpl extends ServiceImpl<PlatformCCourseMapper, PlatformCCourse> implements PlatformCCourseService {

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private PlatformCCourseDeptMapper platformCCourseDeptMapper;

    @Autowired
    private PlatformCCourseOutlineMapper platformCCourseOutlineMapper;

    @Autowired
    private PlatformTTaskDeptMapper platformTTaskDeptMapper;

    @Autowired
    private PlatformTTaskMapper platformTTaskMapper;

    @Autowired
    private PlatformTScoreMapper platformTScoreMapper;

    @Autowired
    private PlatformTTaskQuestionMapper platformTTaskQuestionMapper;

    @Autowired
    private PlatformEExamMapper platformEExamMapper;

    @Autowired
    private PlatformEExamQuestionMapper platformEExamQuestionMapper;

    @Autowired
    private PlatformEScoreMapper platformEScoreMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PlatformLLearnMapper platformLLearnMapper;

    @Autowired
    private PlatformCSpecialtyMapper platformCSpecialtyMapper;

    @Autowired
    private PlatformSCollectMapper platformSCollectMapper;
    private static final String COURSE_KEY = "learning:course";

    //    private static final String COURSE_STUDENTS_KEY_PREFIX = "course:students:";
    private static final String COURSE_VIEWS_KEY_PREFIX = "course:views:";

    @Override
    public AjaxResult selectPlatformCCourseById(Integer id) {
        // 创建返回对象
        PlatformCCourseVO platformCCourseVO = new PlatformCCourseVO();

        // 获取课程信息
        PlatformCCourse platformCCourse = platformCCourseMapper.selectById(id);
        if (platformCCourse == null) {
            return new AjaxResult(HttpStatus.ERROR, "课程不存在");
        }
        BeanUtils.copyProperties(platformCCourse, platformCCourseVO);

        // 获取课程关联的班级ID列表
        Integer[] classIds = platformCCourseDeptMapper.selectByCourseId(id);
        platformCCourseVO.setClassIds(classIds);

        // 获取课程大纲
        List<PlatformCCourseOutline> outlines = platformCCourseOutlineMapper.selectListByCourseId(id);

        // 构建课程大纲树形结构
        List<PlatformCCourseOutlineNodeVO> outlineTree = buildTree(outlines, id);
        platformCCourseVO.setOutline(outlineTree);

        // 获取专业相关信息
        PlatformCSpecialty platformCSpecialty = platformCSpecialtyMapper.selectById(platformCCourseVO.getProfessionalCategoryId());
        platformCCourseVO.setProfessionalCategoryName(platformCSpecialty.getSpecialtyName());
        PlatformCSpecialty platformCSpecialty1 = platformCSpecialtyMapper.selectById(platformCCourseVO.getProfessionalId());
        platformCCourseVO.setProfessionalName(platformCSpecialty1.getSpecialtyName());

        // 添加课程角标状态
        toSetCourseLabelStatus(platformCCourseVO);

        // 获取该课程是否被收藏
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id", userId).eq("collect_type", 1).eq("project_id", platformCCourse.getId());
            int collectCount = Math.toIntExact(platformSCollectMapper.selectCount(queryWrapper));
            platformCCourseVO.setCollect(collectCount > 0 ? 1 : 0);
        } catch (ServiceException e) {
            platformCCourseVO.setCollect(0);
        }
        // 添加上传人所属学校
        String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, platformCCourseVO.getCreateId().longValue());
        if (!"".equals(topLevelSchoolName)) {
            platformCCourseVO.setUploadPersonSchool(topLevelSchoolName);
        }

        // 添加学习人数
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("project_id", platformCCourse.getId()).eq("learn_type", 1);
        List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(platformLLearnQueryWrapper);
        List<PlatformLLearn> newList = new ArrayList<>();
        platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                .forEach(newList::add);
        platformCCourseVO.setLearnNumber(newList.size());

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功", platformCCourseVO);
    }

    /**
     * 构建树形结构
     *
     * @param outlines 课程大纲列表
     * @return 树形结构的课程大纲列表
     */
    private List<PlatformCCourseOutlineNodeVO> buildTree(List<PlatformCCourseOutline> outlines, Integer courseId) {
        // 按照父ID进行分组
        Map<Integer, List<PlatformCCourseOutline>> outlineMap = outlines.stream()
                .collect(Collectors.groupingBy(PlatformCCourseOutline::getParentId));

        // 递归构建树形结构
        return buildTreeRecursively(outlineMap, 0, courseId);
    }

    /**
     * 递归构建树形结构
     *
     * @param outlineMap 按父ID分组的课程大纲 Map（key: 父ID, value: 课程大纲列表）
     * @param parentId   当前节点的父ID
     * @param courseId   课程ID
     * @return 树形结构的课程大纲节点列表
     */
    private List<PlatformCCourseOutlineNodeVO> buildTreeRecursively(Map<Integer, List<PlatformCCourseOutline>> outlineMap, int parentId, Integer courseId) {
        List<PlatformCCourseOutlineNodeVO> nodes = new ArrayList<>();

        // 获取当前层级的课程大纲列表
        List<PlatformCCourseOutline> outlines = outlineMap.get(parentId);

        // 从 Redis 获取该课程的学习记录（key: sectionId, value: 已学习的文件 URL 集合）
        Map<Long, Set<String>> courseLearningRecords = UniversalUtil.getCourseLearningRecords(Long.valueOf(courseId), redisCache);

        if (outlines != null) {
            for (PlatformCCourseOutline outline : outlines) {
                // 创建 VO 对象，并复制属性
                PlatformCCourseOutlineNodeVO node = new PlatformCCourseOutlineNodeVO();
                BeanUtils.copyProperties(outline, node);

                // 解析 JSON 格式的 courseUrl 字段，转换为文件信息列表
                String courseUrl = node.getCourseUrl();
                List<modelFileInfoVO> modelFileInfoVOS = new ArrayList<>();
                if (StringUtils.isNotBlank(courseUrl)) {
                    modelFileInfoVOS = JSONArray.parseArray(courseUrl, modelFileInfoVO.class);
                }

                // 获取当前节点的 sectionId
                Long sectionId = node.getId().longValue();

                // 标记章节是否已学习
                boolean allFilesLearned = !modelFileInfoVOS.isEmpty(); // 假设所有文件都已学习（如果没有文件，则不会被误判）

                // 获取已学习的文件 URL 集合
                if(courseLearningRecords != null && !courseLearningRecords.isEmpty()){
                    Set<String> learnedFiles = courseLearningRecords.getOrDefault(sectionId, new HashSet<>());

                    if (!learnedFiles.isEmpty()) {
                        // 遍历所有的文件信息
                        for (modelFileInfoVO modelFileInfoVO : modelFileInfoVOS) {
                            String fileUrl = modelFileInfoVO.getUrl(); // 完整的 URL
                            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); // 提取文件名

                            // 直接用 Set.contains() 代替遍历，提高性能
                            boolean isLearned = learnedFiles.contains(fileName);

                            // 设置学习状态
                            modelFileInfoVO.setUid(isLearned ? 1L : 0L);

                            // 只要有一个文件未学习，章节就不能标记为 `study = 1`
                            if (!isLearned) {
                                allFilesLearned = false;
                            }
                        }
                    } else {
                        // Redis 没有该 sectionId 的学习记录，则所有文件都标记为未学习
                        for (modelFileInfoVO modelFileInfoVO : modelFileInfoVOS) {
                            modelFileInfoVO.setUid(0L);
                        }
                        allFilesLearned = false; // 章节未学习
                    }
                }
                // 设置课程 URL
                node.setCourseUrl(JSONArray.toJSONString(modelFileInfoVOS));

                // 章节学习状态（如果章节下没有文件，默认为未学习）
                node.setStudy(allFilesLearned ? 1 : 0);

                // 递归构建子节点
                node.setChildren(buildTreeRecursively(outlineMap, outline.getId(), courseId));

                // 添加到返回列表
                nodes.add(node);
            }
        }

        return nodes;
    }


    @Override
    public AjaxResult selectPlatformCCourseList(Integer professionalCategoryId, Integer professionalId, Integer courseVisible) {
        QueryWrapper<PlatformCCourse> queryWrapper = new QueryWrapper<>();

        // 添加查询条件
        int personId = SecurityUtils.getUserId().intValue();
        queryWrapper.eq("create_id", personId);
        if (professionalCategoryId != null) {
            queryWrapper.eq("professional_category_id", professionalCategoryId);
        }
        if (professionalId != null) {
            queryWrapper.eq("professional_id", professionalId);
        }
        if (courseVisible != null) {
            queryWrapper.eq("course_visible", courseVisible);
        }
        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");

        // 查询课程列表
        List<PlatformCCourse> platformCCourses = platformCCourseMapper.selectList(queryWrapper);

        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return new AjaxResult(HttpStatus.UNAUTHORIZED, "用户未登录", null);
        }
        int userIdInt = userId.intValue();

        // 过滤仅自己可见的课程
        platformCCourses = platformCCourses.stream()
                .filter(course -> course.getCourseVisible() == null || course.getCourseVisible() != 2 || (course.getCreateId() != null && course.getCreateId().equals(userIdInt)))
                .collect(Collectors.toList());

        // 添加课程角标状态，构建结果
        ArrayList<PlatformCCourseVO> platformCCourseVOS = new ArrayList<>();
        for (PlatformCCourse platformCCourse : platformCCourses) {
            PlatformCCourseVO platformCCourseVO = new PlatformCCourseVO();
            BeanUtils.copyProperties(platformCCourse, platformCCourseVO);
            toSetCourseLabelStatus(platformCCourseVO);
            platformCCourseVOS.add(platformCCourseVO);
        }
        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功", platformCCourseVOS);
    }

    private void toSetCourseLabelStatus(PlatformCCourseVO platformCCourseVO) {
        if (platformCCourseVO.getVettingStatus() == 0) {
            platformCCourseVO.setCourseLabelStatus(0);
        } else if (platformCCourseVO.getVettingStatus() == 2) {
            platformCCourseVO.setCourseLabelStatus(1);
        } else if (platformCCourseVO.getVettingStatus() == 1 && platformCCourseVO.getCourseStatus() == 0) {
            platformCCourseVO.setCourseLabelStatus(2);
        } else if (platformCCourseVO.getVettingStatus() == 1 && platformCCourseVO.getCourseStatus() == 1) {
            platformCCourseVO.setCourseLabelStatus(3);
        }
    }


    @Override
    public AjaxResult selectPlatformCCourseListStudent() {
        Long userId = SecurityUtils.getUserId();
        int roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        if (roleId != 4) {
            return new AjaxResult(HttpStatus.ERROR, "请使用身份为学生的账号登录");
        }
        int deptId = Integer.parseInt(sysUserMapper.selectUserById(userId).getClassId());
        Integer[] courseIds = platformCCourseDeptMapper.selectByDeptId(deptId);
        ArrayList<PlatformCCourse> platformCCourses = new ArrayList<>();
        for (Integer courseId : courseIds) {
            PlatformCCourse platformCCourse = platformCCourseMapper.selectById(courseId);
            if (platformCCourse.getVettingStatus() == 1) {
                platformCCourses.add(platformCCourse);
            }
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCourses);
    }

    @Override
    public AjaxResult selectPlatformCCourseListStudentTask() {
        // 获取当前用户的部门ID
        Long userId = SecurityUtils.getUserId();
        int roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        if (roleId != 4) {
            return new AjaxResult(HttpStatus.ERROR, "请使用身份为学生的账号登录");
        }
        if(StringUtils.isBlank(sysUserMapper.selectUserById(userId).getClassId())){
            return new AjaxResult(HttpStatus.ERROR, "请先选择班级");
        }
        int deptId = Integer.parseInt(sysUserMapper.selectUserById(userId).getClassId());

        // 根据部门ID查询相关的任务ID
        Integer[] taskIds = platformTTaskDeptMapper.selectByDeptId(deptId);

        // 如果没有相关任务，直接返回空结果
        if (taskIds == null || taskIds.length == 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", Collections.emptyList());
        }

        // 查询任务表中对应的任务
        QueryWrapper<PlatformTTask> taskWrapper = new QueryWrapper<>();
        taskWrapper.in("id", taskIds);
        List<PlatformTTask> platformTTasks = platformTTaskMapper.selectList(taskWrapper);

        // 提取任务中涉及的课程ID
        Set<Integer> courseIds = platformTTasks.stream()
                .map(PlatformTTask::getTaskCourse)
                .collect(Collectors.toSet());

        // 如果没有相关课程，直接返回空结果
        if (courseIds.isEmpty()) {
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", Collections.emptyList());
        }

        // 查询课程表中对应的课程
        QueryWrapper<PlatformCCourse> courseWrapper = new QueryWrapper<>();
        courseWrapper.in("id", courseIds);
        List<PlatformCCourse> platformCCourses = platformCCourseMapper.selectList(courseWrapper);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCourses);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult insertPlatformCCourse(PlatformCCourseVO platformCCourseVO) {
        // 创建PlatformCCourse对象，并复制属性
        PlatformCCourse platformCCourse = new PlatformCCourse();
        BeanUtils.copyProperties(platformCCourseVO, platformCCourse);

        // 设置通用属性
        UniversalCreateUpdate createUpdate = UniversalUtil.getCreateUpdate(sysUserMapper);
        Date nowDate = DateUtils.getNowDate();
        platformCCourse.setCreateTime(nowDate);
        platformCCourse.setCreateBy(createUpdate.getName());
        platformCCourse.setCreateId(createUpdate.getId());
        platformCCourse.setTeacherName(createUpdate.getName());

        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            // 未登录用户，按普通用户处理
        } catch (ServiceException e) {

        }
        int roleId = 0;
        if (userId != null) {
            roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        }
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6);// 超级管理员
        if (roleSystemAdmin) {
            platformCCourse.setVettingStatus(1);
        } else {
            platformCCourse.setVettingStatus(0);
        }

        // 插入课程信息
        int insert = platformCCourseMapper.insert(platformCCourse);
        if (insert <= 0) {
            throw new RuntimeException("新增失败");
        }

        Integer id = platformCCourse.getId();
        // 将授课班级和课程做关联
        insertDeptToTeacher(id, platformCCourseVO.getClassIds());
        // 将大纲和课程做关联
        insertOutlineToCourse(id, platformCCourseVO.getOutline(), 0);

        return new AjaxResult(HttpStatus.SUCCESS, "新增成功");
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult updatePlatformCCourse(PlatformCCourseVO platformCCourseVO) {
        // 创建PlatformCCourse对象，并复制属性
        PlatformCCourse platformCCourse = new PlatformCCourse();
        BeanUtils.copyProperties(platformCCourseVO, platformCCourse);

        // 设置通用属性
        UniversalCreateUpdate createUpdate = UniversalUtil.getCreateUpdate(sysUserMapper);
        Date nowDate = DateUtils.getNowDate();
        platformCCourse.setUpdateTime(nowDate);
        platformCCourse.setUpdateBy(createUpdate.getName());
        platformCCourse.setUpdateId(createUpdate.getId());

        // 如果是未通过的课程再次修改，那么将之前的审核信息置空
        if (platformCCourse.getVettingStatus() != null && platformCCourse.getVettingStatus() == 2) {
            platformCCourse.setVettingStatus(0);
            // platformCCourse.setNotPassingReason(null);
            // platformCCourse.setNotPassingType(null);
        }

        // 修改课程信息
        int update = platformCCourseMapper.updateById(platformCCourse);
        if (update <= 0) {
            throw new RuntimeException("修改失败");
        }

        Integer id = platformCCourse.getId();
        // 删除授课班级和课程关联
        deleteDeptToTeacher(id);
        // 将授课班级和课程做关联
        insertDeptToTeacher(id, platformCCourseVO.getClassIds());
        // 修改课程和大纲的关联
        updateOutlineToCourse(id, platformCCourseVO.getOutline());
        // 如果有删除的大纲，执行删除操作
        List<Integer> deleteOutlineIds = platformCCourseVO.getDeleteOutlineIds();
        if (!CollectionUtils.isEmpty(deleteOutlineIds)) {
            // 先校验大纲有没有被发布作业
            QueryWrapper<PlatformTTask> chapter = new QueryWrapper<>();
            chapter.in("task_chapter", deleteOutlineIds);
            List<PlatformTTask> platformTTasksChapter = platformTTaskMapper.selectList(chapter);
            QueryWrapper<PlatformTTask> part = new QueryWrapper<>();
            part.in("task_part", deleteOutlineIds);
            List<PlatformTTask> platformTTasksPart = platformTTaskMapper.selectList(part);
            if (!CollectionUtils.isEmpty(platformTTasksChapter)) {
                Integer taskChapter = platformTTasksChapter.get(0).getTaskChapter();
                PlatformCCourseOutline platformCCourseOutline = platformCCourseOutlineMapper.selectById(taskChapter);
                throw new RuntimeException("所删章节【" + platformCCourseOutline.getName() + "】已被作业【" + platformTTasksChapter.get(0).getTaskName() + "】使用，无法删除，请刷新后重试");
            }
            if (!CollectionUtils.isEmpty(platformTTasksPart)) {
                Integer taskPart = platformTTasksPart.get(0).getTaskPart();
                PlatformCCourseOutline platformCCourseOutline = platformCCourseOutlineMapper.selectById(taskPart);
                throw new RuntimeException("所删课时【" + platformCCourseOutline.getName() + "】已被作业【" + platformTTasksPart.get(0).getTaskName() + "】使用，无法删除，请刷新后重试");
            }
            platformCCourseOutlineMapper.deleteBatchIds(deleteOutlineIds);
        }

        return new AjaxResult(HttpStatus.SUCCESS, "修改成功");
    }

    private void updateOutlineToCourse(Integer courseId, List<PlatformCCourseOutlineNodeVO> outlines) {
        List<PlatformCCourseOutlineNodeVO> newOutlines = new ArrayList<>();

        // 遍历所有大纲节点
        for (PlatformCCourseOutlineNodeVO outline : outlines) {
            if (outline.getId() != null) {
                // 如果大纲节点已经有ID，表示需要更新
                PlatformCCourseOutline platformCCourseOutline = new PlatformCCourseOutline();
                BeanUtils.copyProperties(outline, platformCCourseOutline);
                platformCCourseOutline.setCourseId(courseId);

                // 更新大纲节点信息
                platformCCourseOutlineMapper.updateById(platformCCourseOutline);

                // 递归更新子节点
                if (!CollectionUtils.isEmpty(outline.getChildren())) {
                    updateOutlineChildrenToCourse(courseId, outline.getChildren(), outline.getId());
                }
            } else {
                // 如果大纲节点没有ID，表示需要新增
                newOutlines.add(outline);
            }
        }

        // 插入新增的大纲节点
        if (!CollectionUtils.isEmpty(newOutlines)) {
            insertOutlineToCourse(courseId, newOutlines, 0);
        }
    }

    private void updateOutlineChildrenToCourse(Integer courseId, List<PlatformCCourseOutlineNodeVO> children, Integer parentId) {
        for (PlatformCCourseOutlineNodeVO child : children) {
            if (null != child.getId()) {
                // 如果大纲子节点已经有ID，表示需要更新
                PlatformCCourseOutline platformCCourseOutline = new PlatformCCourseOutline();
                BeanUtils.copyProperties(child, platformCCourseOutline);
                platformCCourseOutline.setCourseId(courseId);

                // 更新大纲子节点信息
                platformCCourseOutlineMapper.updateById(platformCCourseOutline);
            } else {
                Date nowDate = DateUtils.getNowDate();
                UniversalCreateUpdate createUpdate = UniversalUtil.getCreateUpdate(sysUserMapper);
                PlatformCCourseOutline platformCCourseOutline = new PlatformCCourseOutline();
                BeanUtils.copyProperties(child, platformCCourseOutline);
                platformCCourseOutline.setCourseId(courseId);
                platformCCourseOutline.setParentId(parentId);
                // 设置通用属性
                platformCCourseOutline.setCreateTime(nowDate);
                platformCCourseOutline.setCreateBy(createUpdate.getName());
                platformCCourseOutline.setCreateId(createUpdate.getId());
                platformCCourseOutline.setCourseId(courseId);
                platformCCourseOutline.setParentId(parentId);
                // 新增大纲子节点信息
                platformCCourseOutlineMapper.insert(platformCCourseOutline);
            }
//            // 递归处理子节点
//            if (!CollectionUtils.isEmpty(child.getChildren())) {
//                updateOutlineChildrenToCourse(courseId, child.getChildren(), child.getId());
//            }
        }
    }

    private void insertOutlineToCourse(Integer courseId, List<PlatformCCourseOutlineNodeVO> outlines, Integer parentId) {
        if (CollectionUtils.isEmpty(outlines)) {
            return;
        }

        Date nowDate = DateUtils.getNowDate();
        UniversalCreateUpdate createUpdate = UniversalUtil.getCreateUpdate(sysUserMapper);

        for (PlatformCCourseOutlineNodeVO outlineNode : outlines) {
            PlatformCCourseOutline outline = new PlatformCCourseOutline();
            BeanUtils.copyProperties(outlineNode, outline);

            // 设置通用属性
            outline.setCreateTime(nowDate);
            outline.setCreateBy(createUpdate.getName());
            outline.setCreateId(createUpdate.getId());
            outline.setCourseId(courseId);
            outline.setParentId(parentId);

            // 插入课程大纲
            platformCCourseOutlineMapper.insertPlatformCCourseOutline(outline);

            // 递归插入子节点
            if (!CollectionUtils.isEmpty(outlineNode.getChildren())) {
                insertOutlineToCourse(courseId, outlineNode.getChildren(), outline.getId());
            }
        }
    }


    private void insertDeptToTeacher(Integer courseId, Integer[] classIds) {
        if (classIds == null || classIds.length == 0) {
            return;
        }

        for (Integer classId : classIds) {
            PlatformCCourseDept courseDept = new PlatformCCourseDept();
            courseDept.setCourseId(courseId);
            courseDept.setDeptId(classId);

            // 插入课程和班级关联
            platformCCourseDeptMapper.insert(courseDept);
        }
    }

    private void deleteOutlineToCourse(Integer id) {
        platformCCourseOutlineMapper.deleteByCourseId(id);
    }

    private void deleteDeptToTeacher(Integer id) {
        platformCCourseDeptMapper.deleteByCourseId(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformCCourseByIds(Long[] ids) {
        int length = ids.length;
        int successCount = 0;

        for (Long id : ids) {
            int deleteCount = platformCCourseMapper.deleteById(id);
            if (deleteCount > 0) {
                successCount++;
                int idInt = id.intValue();
                // 删除授课班级和课程关联
                deleteDeptToTeacher(idInt);
                // 删除大纲和课程关联
                deleteOutlineToCourse(idInt);
                // 删除考试、考试试题、考试学生成绩和课程的管理
                deleteExamAndQuestionAndStudent(idInt);
                // 删除作业、作业班级、作业试题、作业学生成绩和课程的关联
                deleteHomeworkAndClassAndQuestionAndStudent(idInt);
                // 删除收藏与课程的关联
                deleteCollectAndCourse(idInt);
                // 删除学习记录和课程的关联
                deleteLearnAndCourse(idInt);
            }
        }

        if (successCount == length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }

    private void deleteLearnAndCourse(int idInt) {
        QueryWrapper<PlatformLLearn> platformSLearnRecordQueryWrapper = new QueryWrapper<>();
        platformSLearnRecordQueryWrapper.eq("project_id", idInt);
        platformSLearnRecordQueryWrapper.eq("learn_type", 1);
        platformLLearnMapper.delete(platformSLearnRecordQueryWrapper);
    }

    private void deleteCollectAndCourse(int idInt) {
        QueryWrapper<PlatformSCollect> platformSCollectQueryWrapper = new QueryWrapper<>();
        platformSCollectQueryWrapper.eq("collect_type", 1);
        platformSCollectQueryWrapper.eq("project_id", idInt);
        platformSCollectMapper.delete(platformSCollectQueryWrapper);
    }

    private void deleteHomeworkAndClassAndQuestionAndStudent(int idInt) {
        QueryWrapper<PlatformTTask> platformTTaskQueryWrapper = new QueryWrapper<>();
        platformTTaskQueryWrapper.eq("task_course", idInt);
        List<PlatformTTask> platformTTasks = platformTTaskMapper.selectList(platformTTaskQueryWrapper);
        if (!CollectionUtils.isEmpty(platformTTasks)) {
            for (PlatformTTask platformTTask : platformTTasks) {
                Integer taskId = platformTTask.getId();
                long ltaskId = taskId.longValue();
                platformTTaskDeptMapper.deleteByTaskId(ltaskId);
                platformTTaskMapper.deleteById(taskId);
                platformTTaskQuestionMapper.deleteByTaskId(ltaskId);
                platformTScoreMapper.deleteByTaskId(ltaskId);
            }
        }
    }

    private void deleteExamAndQuestionAndStudent(int idInt) {
        QueryWrapper<PlatformEExam> platformEExamQueryWrapper = new QueryWrapper<>();
        platformEExamQueryWrapper.eq("exam_course", idInt);
        List<PlatformEExam> platformEExams = platformEExamMapper.selectList(platformEExamQueryWrapper);
        if (!CollectionUtils.isEmpty(platformEExams)) {
            for (PlatformEExam platformEExam : platformEExams) {
                Integer examId = platformEExam.getId();
                long lexamId = examId.longValue();
                platformEExamQuestionMapper.deleteByExamId(lexamId);
                platformEExamMapper.deleteById(examId);
                platformEScoreMapper.deleteByExamId(lexamId);
            }
        }
    }

    /**
     * @param pageNum                页码
     * @param pageSize               条数
     * @param professionalCategoryId 专业大类id
     * @param professionalId         专业分类id
     * @param courseVisible          课程分类（0云课堂，1专业授课，999全部）
     * @param sortord                排序方式（0默认先按评分再按上传时间，1最新时间，999全部）
     * @param courseStatus           课程状态（0开课，1结课，999全部）
     * @param courseName             课程名称
     * @return
     */
    @Override
    public AjaxResult selectPlatformCCourseListUser(Integer pageNum, Integer pageSize, Integer professionalCategoryId, Integer professionalId, Integer courseVisible, Integer sortord, String courseName, Integer courseStatus) {
        if (StringUtils.isNotEmpty(courseName)) {
            // 记录搜索词，类型为"2在线课程"
            redisCache.recordSearchTerm(2, courseName);
        }
        // 如果课程状态为999，则将其置为null以忽略该条件
        if (courseStatus != null && courseStatus == 999) {
            courseStatus = null;
        }

        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            // 未登录用户，按普通用户处理
        } catch (ServiceException e) {

        }
        int roleId = 0;
        if (userId != null) {
            roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        }
        boolean roleUser = (roleId == 5 || roleId == 0 || roleId == 7);// 普通用户和企业用户
        boolean roleTeacher = (roleId == 3);// 教师
        boolean roleStudent = (roleId == 4);// 学生
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6);// 超级管理员
        boolean roleSchoolAdmin = (roleId == 2);// 学校管理员
        platformCCourseQueryWrapper.eq("course_visible", 0);    // 查询云课堂
        List<PlatformCCourse> platformCCourses = platformCCourseMapper.selectList(platformCCourseQueryWrapper);
        if (roleUser) {
            if (null != courseVisible && courseVisible == 1) {
                return new AjaxResult(HttpStatus.SUCCESS, "查询成功", new Page<>(pageNum, pageSize));
            }
            if (null != professionalCategoryId && professionalCategoryId != 999) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalCategoryId() != professionalCategoryId);
            }
            if (null != professionalId && professionalId != 999) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalId() != professionalId);
            }
            if (StringUtils.isNotEmpty(courseName)) {
                if (StringUtils.isNotEmpty(courseName)) {
                    platformCCourses.removeIf(platformCCourse ->
                            !(platformCCourse.getCourseName().contains(courseName) || platformCCourse.getCreateBy().contains(courseName))
                    );
                }
            }
            if (null != courseStatus) {
                Integer finalCourseStatus = courseStatus;
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseStatus() != finalCourseStatus);
            }
        }
        if (roleTeacher) {
            int teacherId = SecurityUtils.getUserId().intValue();
            QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("create_id", teacherId);
            wrapper.ne("course_visible", 0);     // 除去云课堂
            List<PlatformCCourse> teacherOwn = platformCCourseMapper.selectList(wrapper);
            if (!CollectionUtils.isEmpty(teacherOwn)) {
                platformCCourses.addAll(teacherOwn);
            }
            filterCourse(professionalCategoryId, professionalId, courseVisible, courseName, courseStatus, platformCCourses);
        }
        if (roleStudent) {
            int deptId = 0;
            try {
                if (null != sysUserMapper.selectUserById(userId).getClassId()) {
                    deptId = Integer.parseInt(sysUserMapper.selectUserById(userId).getClassId());
                }
            } catch (ServiceException e) {

            }
            List<PlatformCCourse> studentCourse = new ArrayList<>();
            if (deptId != 0) {
                Integer[] courseId = platformCCourseDeptMapper.selectByDeptId(deptId);
                if (!CollectionUtils.isEmpty(Arrays.asList(courseId))) {
                    QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
                    wrapper.in("id", Arrays.asList(courseId));
                    wrapper.ne("course_visible", 0);     // 除去云课堂
                    studentCourse = platformCCourseMapper.selectList(wrapper);
                }
                if (!CollectionUtils.isEmpty(studentCourse)) {
                    platformCCourses.addAll(studentCourse);
                }
            }
            if (null != professionalCategoryId && professionalCategoryId != 999) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalCategoryId() != professionalCategoryId);
            }
            if (null != professionalId && professionalId != 999) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalId() != professionalId);
            }
            if (null != courseStatus) {
                Integer finalCourseStatus = courseStatus;
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseStatus() != finalCourseStatus);
            }
            if (null != courseVisible && courseVisible != 999) {
                if (courseVisible == 0) {
                    platformCCourses.removeAll(studentCourse);
                    Page<PlatformCCourseVO> page = toPage(platformCCourses, pageNum, pageSize, sortord);
                    return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
                }
                if (courseVisible == 1) {
                    platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseVisible() != courseVisible);
                }
            }
            if (StringUtils.isNotEmpty(courseName)) {
                if (StringUtils.isNotEmpty(courseName)) {
                    platformCCourses.removeIf(platformCCourse ->
                            !(platformCCourse.getCourseName().contains(courseName) || platformCCourse.getCreateBy().contains(courseName))
                    );
                }
            }
        }
        if (roleSystemAdmin) {
            QueryWrapper<PlatformCCourse> systemAdminQW = new QueryWrapper<>();
            systemAdminQW.eq("vetting_status", 1);
            systemAdminQW.ne("course_visible", 2);
            List<PlatformCCourse> systemAdminCourses = platformCCourseMapper.selectList(systemAdminQW);
            filterCourse(professionalCategoryId, professionalId, courseVisible, courseName, courseStatus, systemAdminCourses);
            Page<PlatformCCourseVO> page = toPage(systemAdminCourses, pageNum, pageSize, sortord);
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
        }
        if (roleSchoolAdmin) {
            Long schoolAdminDeptId = Long.parseLong(sysUserMapper.selectUserById(userId).getClassId());
            List<SysDept> collegeDepts = sysDeptMapper.selectChildrenDeptById(schoolAdminDeptId);
            List<Long> specialtyDeptIds = new ArrayList<>();
            List<Long> teacherIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(collegeDepts)) {
                for (SysDept collegeDept : collegeDepts) {
                    List<SysDept> collegeDeptInfo = sysDeptMapper.selectChildrenDeptById(collegeDept.getDeptId());
                    if (CollectionUtils.isEmpty(collegeDeptInfo)) {
                        continue;
                    }
                    for (SysDept specialtyDept : collegeDeptInfo) {
                        specialtyDeptIds.add(specialtyDept.getDeptId());
                    }
                }
                if (!CollectionUtils.isEmpty(specialtyDeptIds)) {
                    for (Long specialtyDeptId : specialtyDeptIds) {
                        List<WorkDeptUserVO> workDeptUserVOS = sysUserMapper.selectDeptUsers(specialtyDeptId);
                        for (WorkDeptUserVO workDeptUserVO : workDeptUserVOS) {
                            teacherIds.add(workDeptUserVO.getId());
                        }
                    }
                }
            }
            QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
            List<PlatformCCourse> schoolAdminCourses = new ArrayList<>();
            if (!CollectionUtils.isEmpty(teacherIds)) {
                wrapper.in("create_id", teacherIds);
                wrapper.ne("course_visible", 2);
                schoolAdminCourses = platformCCourseMapper.selectList(wrapper);
                schoolAdminCourses.removeIf(platformCCourse -> platformCCourse.getCourseVisible() == 0);// 删除云课堂
            }
            if (!CollectionUtils.isEmpty(schoolAdminCourses)) {
                platformCCourses.removeAll(schoolAdminCourses);
            }
            filterCourse(professionalCategoryId, professionalId, courseVisible, courseName, courseStatus, platformCCourses);
        }
        Page<PlatformCCourseVO> page = toPage(platformCCourses, pageNum, pageSize, sortord);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
    }

    private void filterCourse(Integer professionalCategoryId, Integer professionalId, Integer courseVisible, String courseName, Integer courseStatus, List<PlatformCCourse> platformCCourses) {
        if (null != professionalCategoryId && professionalCategoryId != 999) {
            platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalCategoryId() != professionalCategoryId);
        }
        if (null != professionalId && professionalId != 999) {
            platformCCourses.removeIf(platformCCourse -> platformCCourse.getProfessionalId() != professionalId);
        }
        if (null != courseVisible && courseVisible != 999) {
            if (courseVisible == 0) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseVisible() != courseVisible);
            }
            if (courseVisible == 1) {
                platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseVisible() != courseVisible);
            }
        }
        if (StringUtils.isNotEmpty(courseName)) {
            if (StringUtils.isNotEmpty(courseName)) {
                platformCCourses.removeIf(platformCCourse ->
                        !(platformCCourse.getCourseName().contains(courseName) || platformCCourse.getCreateBy().contains(courseName))
                );
            }
        }
        if (null != courseStatus) {
            platformCCourses.removeIf(platformCCourse -> platformCCourse.getCourseStatus() != courseStatus);
        }
    }

    private Page<PlatformCCourseVO> toPage(List<PlatformCCourse> courses, Integer pageNum, Integer pageSize, Integer sortord) {
        // 过滤未审核通过的课程
        courses.removeIf(course -> course.getVettingStatus() != 1);

        // 排序逻辑
        if (sortord != null && sortord == 1) {
            // 按最新时间排序
            courses.sort(Comparator.comparing(PlatformCCourse::getCreateTime).reversed());
        } else {
            // 默认按评分排序，再按上传时间排序
            courses.sort(Comparator.comparing(PlatformCCourse::getGrade).reversed()
                    .thenComparing(Comparator.comparing(PlatformCCourse::getCreateTime).reversed()));
        }

        // 确定分页参数
        int total = courses.size();
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);

        // 获取当前页的数据
        List<PlatformCCourse> paginatedList = courses.subList(start, end);

        // 创建存储结果的列表
        ArrayList<PlatformCCourseVO> platformCCourseVOS = new ArrayList<>();

        // 获取用户ID，如果无法获取则捕获异常
        Integer userId = null;
        try {
            userId = SecurityUtils.getUserId().intValue();
        } catch (ServiceException e) {
            // 无法获取用户ID时，设置用户ID为null
        }

        for (PlatformCCourse platformCCourse : paginatedList) {
            PlatformCCourseVO platformCCourseVO = new PlatformCCourseVO();
            BeanUtils.copyProperties(platformCCourse, platformCCourseVO);

            if (userId == null) {
                // 如果无法获取用户ID，直接添加学习人数
                QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
                platformLLearnQueryWrapper.eq("project_id", platformCCourse.getId()).eq("learn_type", 1);
                List<PlatformLLearn> newList = new ArrayList<>();
                List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(platformLLearnQueryWrapper);
                platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                        .forEach(newList::add);
                platformCCourseVO.setLearnNumber(newList.size());
                platformCCourseVOS.add(platformCCourseVO);
            } else {
                // 获取该课程是否被收藏
                QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", userId).eq("collect_type", 1).eq("project_id", platformCCourse.getId());
                int collectCount = Math.toIntExact(platformSCollectMapper.selectCount(queryWrapper));
                platformCCourseVO.setCollect(collectCount > 0 ? 1 : 0);

                // 添加学习人数
                QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
                platformLLearnQueryWrapper.eq("project_id", platformCCourse.getId()).eq("learn_type", 1);
                List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(platformLLearnQueryWrapper);
                List<PlatformLLearn> newList = new ArrayList<>();
                platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                        .forEach(newList::add);
                platformCCourseVO.setLearnNumber(newList.size());

                platformCCourseVOS.add(platformCCourseVO);
            }
        }

        // 设置分页信息
        Page<PlatformCCourseVO> page = new Page<>(pageNum, pageSize);
        page.setRecords(platformCCourseVOS);
        page.setTotal(total);

        return page;
    }


    /**
     * @param pageNum                页码
     * @param pageSize               条数
     * @param courseName             课程名称
     * @param createBy               发布者
     * @param professionalCategoryId 专业分类id（大类）
     * @param vettingStatus          审核状态（0未审批，1已通过，2未通过）
     * @return
     */
    @Override
    public AjaxResult selectPlatformCCourseListSystemAdmin(Integer pageNum, Integer pageSize, String courseName, String createBy, Integer professionalCategoryId, Integer vettingStatus) {
        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        Page<PlatformCCourse> platformCCoursePage = new Page<>(pageNum, pageSize);
        if (null != courseName && !courseName.equals("")) {
            platformCCourseQueryWrapper.like("course_name", courseName);
        }
        if (null != createBy && !createBy.equals("")) {
            platformCCourseQueryWrapper.like("create_by", createBy);
        }
        if (null != professionalCategoryId) {
            platformCCourseQueryWrapper.eq("professional_category_id", professionalCategoryId);
        }
        if (null != vettingStatus) {
            platformCCourseQueryWrapper.eq("vetting_status", vettingStatus);
        }
        platformCCourseQueryWrapper.orderByDesc("id");
        IPage<PlatformCCourse> platformCCourseIPage = platformCCourseMapper.selectPage(platformCCoursePage, platformCCourseQueryWrapper);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCourseIPage);
    }

    @Override
    public AjaxResult updatePlatformCCourseVetting(VettingRequest vettingRequest) {
        PlatformCCourse platformCCourse = new PlatformCCourse();
        BeanUtils.copyProperties(vettingRequest, platformCCourse);
        int u = platformCCourseMapper.updateById(platformCCourse);
        if (u > 0) {
            if (vettingRequest.getVettingStatus() == 1) {
                PlatformCCourse platformCCourse1 = platformCCourseMapper.selectById(vettingRequest.getId());
                if (platformCCourse1.getCourseVisible() == 1) {
                    Integer course1Id = platformCCourse1.getId();
                    Integer[] integers = platformCCourseDeptMapper.selectByCourseId(course1Id);
                    for (Integer classId : integers) {
                        // 审核通过给学生发放课程
                        List<SysUser> sysUsers = sysUserMapper.selectUserByDeptId(String.valueOf(classId));
                        for (SysUser sysUser : sysUsers) {
                            PlatformLLearn platformLLearn = new PlatformLLearn();
                            platformLLearn.setProjectId(course1Id);
                            platformLLearn.setLearnType(1);
                            platformLLearn.setLearnPersonId(sysUser.getUserId());
                            UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
                            platformLLearn.setCreateTime(DateUtils.getNowDate());
                            platformLLearn.setCreateBy(create.getName());
                            platformLLearn.setCreateId(create.getId());
                            platformLLearnMapper.insert(platformLLearn);
                        }
                    }
                }
            }
            return new AjaxResult(HttpStatus.SUCCESS, "审核成功");
        } else {
            return new AjaxResult(HttpStatus.SUCCESS, "审核失败，请联系管理员");
        }
    }

    @Override
    public AjaxResult listPassed(Integer finishCourse) {
        int userId = SecurityUtils.getUserId().intValue();
        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        platformCCourseQueryWrapper.eq("create_id", userId);
        platformCCourseQueryWrapper.eq("vetting_status", 1); // 已通过审核
        platformCCourseQueryWrapper.eq("course_visible", 1); // 专业授课
        if (null != finishCourse && finishCourse == 0) {
            platformCCourseQueryWrapper.eq("course_status", finishCourse);
        }
        // 根据 id 字段倒序排序
        platformCCourseQueryWrapper.orderByDesc("id");
        // 查询课程列表
        List<PlatformCCourse> platformCCourses = platformCCourseMapper.selectList(platformCCourseQueryWrapper);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCourses);
    }

    @Override
    public void addCourseView(Integer courseId) {
        String viewKey = COURSE_VIEWS_KEY_PREFIX + courseId;
        redisCache.getIncrementValue(viewKey, "views", 1);
    }

    @Override
    public AjaxResult selectHotSearch() {
        Set<Object> top5SearchTerms = redisCache.getTop5SearchTerms(2);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", top5SearchTerms);
    }

    @Override
    public AjaxResult selectTeacherInfo(Integer userId) {
        long l = userId.longValue();
        SysUser sysUser = sysUserMapper.selectUserById(l);
        TeacherInfoVO teacherInfoVO = new TeacherInfoVO();
        if (null != sysUser) {
            teacherInfoVO.setAvatar(sysUser.getAvatar());
            teacherInfoVO.setNickname(sysUser.getNickName());
            teacherInfoVO.setUserId(sysUser.getUserId());
            // TODO 老师介绍
        }
        // 添加上传人所属学校
        String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, l);
        if (!"".equals(topLevelSchoolName)) {
            teacherInfoVO.setSchoolName(topLevelSchoolName);
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", teacherInfoVO);
    }

    public AjaxResult recordLearning(Long courseId, Long sectionId, String fileUrl) {
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        } catch (ServiceException e) {
            return new AjaxResult(HttpStatus.ERROR, "请先登录");
        }

        // Redis Hash Key
        String redisKey = "user_course:" + userId + ":" + courseId;
        String field = sectionId.toString(); // sectionId 作为 Hash 的 field

        // 获取该小节下的已学习文件集合
        String jsonStr = redisCache.getCacheMapValue(redisKey, field);
        Set<String> fileSet = (jsonStr != null) ? new HashSet<>(JSONArray.parseArray(jsonStr, String.class)) : new HashSet<>();

        // 如果 fileUrl 不为空，才添加
        if (StringUtils.isNotBlank(fileUrl)) {
            fileSet.add(fileUrl);
        }

        // 存回 Redis
        redisCache.setCacheMapValue(redisKey, field, JSONArray.toJSONString(fileSet));

        return AjaxResult.success("学习记录成功");
    }


    @Override
    public AjaxResult listSchoolAdmin(Integer pageNum, Integer pageSize, String courseName, String createBy, Integer professionalCategoryId, Integer vettingStatus) {
        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        Page<PlatformCCourse> platformCCoursePage = new Page<>(pageNum, pageSize);
        Long schoolId = SecurityUtils.getLoginUser().getUser().getSchoolId();
        if (null == schoolId) {
            return new AjaxResult(HttpStatus.ERROR, "暂未分配学校");
        } else {
            List<Long> userIds = new ArrayList<>();
            List<SysUser> userList = sysUserMapper.selectUserListBySchoolId(schoolId);
            if (!CollectionUtils.isEmpty(userList)) {
                userList.forEach(u -> userIds.add(u.getUserId()));
            }
            if (CollectionUtils.isEmpty(userIds)) {
                return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCoursePage);
            }
            platformCCourseQueryWrapper.in("create_id", userIds);
        }
        if (null != courseName && !courseName.equals("")) {
            platformCCourseQueryWrapper.like("course_name", courseName);
        }
        if (null != createBy && !createBy.equals("")) {
            platformCCourseQueryWrapper.like("create_by", createBy);
        }
        if (null != professionalCategoryId) {
            platformCCourseQueryWrapper.eq("professional_category_id", professionalCategoryId);
        }
        if (null != vettingStatus) {
            platformCCourseQueryWrapper.eq("vetting_status", vettingStatus);
        }
        platformCCourseQueryWrapper.orderByDesc("id");
        IPage<PlatformCCourse> platformCCourseIPage = platformCCourseMapper.selectPage(platformCCoursePage, platformCCourseQueryWrapper);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformCCourseIPage);
    }

    @Override
    public void deleteLearningRecord() {
        redisCache.removeCacheSetValue(COURSE_KEY, SecurityUtils.getUserId().intValue());
    }

    //    @Override
//    public void addCourseStudent(Integer courseId) {
//        int userId = SecurityUtils.getUserId().intValue();
//        String studentKey = COURSE_STUDENTS_KEY_PREFIX + courseId;
//        Set<String> students = redisCache.getCacheSet(studentKey);
//
//        if (students == null || !students.contains(String.valueOf(userId))) {
//            redisCache.setCacheSet(studentKey, Collections.singleton(String.valueOf(userId)));
//        }
//    }
}
